/**
 * 
 */
package com.molyfun.provider.user;


import java.util.List;

import com.github.pagehelper.StringUtil;
import com.molyfun.core.Constants;
import com.molyfun.core.base.BaseProviderImpl;
import com.molyfun.core.support.dubbo.spring.annotation.DubboService;
import com.molyfun.core.util.RedisUtil;
import com.molyfun.model.user.HoUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;

import com.molyfun.dao.user.HoUserMapper;

/**
 */
@DubboService(interfaceClass = HoUserProvider.class)
@CacheConfig(cacheNames = "hoUser")
public class HoUserProviderImpl extends BaseProviderImpl<HoUser> implements HoUserProvider {

	@Autowired
	private HoUserMapper hoUserMapper;

	@Override
	public HoUser queryUserByUserNameAndPhone(HoUser user) {
		try {
			List<HoUser> list = hoUserMapper.selectByUserNameAndPhone(user.getUsername(),user.getPassword());
			if(list.size() > 0)
			{
				user = list.get(0);
				String key = getCacheKey(user.getId());
				RedisUtil.set(key, user);
				return user;
			}
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public HoUser queryByPhone(String phone) {
		try {
			List<HoUser> list = hoUserMapper.selectByPhone(phone);
			if(list.size() > 0)
			{
				HoUser user = list.get(0);
				String key = getCacheKey(user.getId());
				RedisUtil.set(key, user);
				return user;
			}
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public HoUser queryByName(String name) {
		try {
			List<HoUser> list = hoUserMapper.selectByName(name);
			if(list.size() > 0)
			{
				HoUser user = list.get(0);
				String key = getCacheKey(user.getId());
				RedisUtil.set(key, user);
				return user;
			}
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/* (non-Javadoc)
	 * @see com.molyfun.provider.user.HoUserProvider#queryByToken(java.lang.String)
	 */
	@Override
	public String queryUserIdByToken(String token) {
		try {

			String key =  new StringBuilder(Constants.CACHE_NAMESPACE).append(Constants.CACHE_TOKEN).append(token).toString();
			String value = (String) RedisUtil.get(key);
			if (StringUtil.isEmpty(value)) 
			{
				String id = hoUserMapper.selectUserIdByToken(token);
				if (StringUtil.isNotEmpty(id)) 
				{
					RedisUtil.set(key,id);
				}
				return id;
			}
			return value;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

}
